//创建用户相关的小仓库
import { defineStore } from 'pinia';
//引入接口
import { reqLogin, reqUserInfo } from '@/api/user';
//引入数据类型
import type {
  loginForm,
  loginResponseData,
  userResponseData,
} from '@/api/user/type';
import type { UserState } from './types/type';
//引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token';
//引入常量路由
import { constantRoute } from '@/router/routes';
import router from '@/router/index';
// @ts-ignore
import cloneDeep from 'lodash/cloneDeep';
//创建用户小仓库
let useUserStore = defineStore('User', {
  //小仓库存储数据地方
  state: (): UserState => {
    return {
      token: GET_TOKEN(), //用户唯一标识token
      menuRoutes: constantRoute, //仓库存储生成菜单需要数据(路由)
      username: '',
      avatar: '',
      name: '',
      userId: 0,
      roleName: [],
    };
  },
  //异步|逻辑的地方
  actions: {
    //用户登录的方法
    async userLogin(data: loginForm) {
      //登录请求
      let result: loginResponseData = await reqLogin(data);
      if (result.code == 200) {
        //pinia仓库存储一下token
        //由于pinia|vuex存储数据其实是利用js对象
        this.token = result.data.token as string;
        //本地存储持久化存储一份
        SET_TOKEN(result.data.token as string);
        //能保证当前async函数返回一个成功的promise
        // await this.userInfo();
        // router.push('/system/user');
        return 'ok';
      } else {
        return Promise.reject(new Error(result.message));
      }
    },
    //获取用户信息的方法
    async userInfo() {
      //获取用户信息进行存储仓库当中[用户头像、名字]
      let result: userResponseData = await reqUserInfo();
      console.log("🚀 ~ userInfo ~ result:", result)

      //如果获取用户信息成功，存储一下用户信息
      if (result.code == 200) {
        if (!(result.data as any)[1]) {
          throw new Error('此用户未分配角色');
        }
        for (const key in result.data) {
          this.roleName.push((result.data as any)[key].roleName);
        }
        this.username = (result.data as any)[1].username;
        this.avatar = (result.data as any)[1].headUrl;
        this.name = (result.data as any)[1].name;
        this.userId = (result.data as any)[1].userId;

        // TODO 获取用户menuList
        // console.log('🦽stringList', (result.data as any)[0].menuListNoTree);

        // let newAsyncRoute = cloneDeep(asyncRoute);
        // const menuStringList: Array<string> = (result.data as any)[0]
        //   .menuListNoTree;
        // console.log('🚀newAsyncRoute', newAsyncRoute);
        // function dfsMenuList(menuList: any) {
        //   return menuList.filter((item: any) => {
        //     if (menuStringList.includes(item.name)) {
        //       if (item.children) {
        //         item.children = dfsMenuList(item.children);
        //       }
        //       return true;
        //     } else {
        //       return false;
        //     }
        //   });
        // }
        // newAsyncRoute = dfsMenuList(newAsyncRoute);

        // [...newAsyncRoute, ...NotFoundRoute].forEach((item: any) => {
        //   router.addRoute(item);
        // });

        // // [x] 计算router“/”的重定向
        // for (let i = 0; i < newAsyncRoute.length; i++) {
        //   if (
        //     newAsyncRoute[i].name === 'Screen' ||
        //     newAsyncRoute[i].name === 'SmartPartor'
        //   ) {
        //     continue;
        //   } else {
        //     if (newAsyncRoute[i].children) {
        //       router.addRoute({
        //         path: '/',
        //         redirect: newAsyncRoute[i].children[0].path,
        //       });
        //     } else {
        //       router.addRoute({
        //         path: '/',
        //         redirect: newAsyncRoute[i].path,
        //       });
        //     }
        //     break;
        //   }
        // }
        // if (newAsyncRoute.length === 1 && newAsyncRoute[0].name === 'Screen') {
        //   router.addRoute({
        //     path: '/',
        //     redirect: newAsyncRoute[0].path + '?screenInfo=only',
        //   });
        // }

        // this.menuRoutes = [...constantRoute, ...newAsyncRoute];

        return 'ok';
      } else {
        return Promise.reject(new Error(result.message));
      }
    },
    //退出登录
    userLogout() {
      this.token = '';
      this.username = '';
      this.avatar = '';
      this.name = '';
      this.roleName = [];
      REMOVE_TOKEN();
    },
  },
  getters: {},
});
//对外暴露获取小仓库方法
export default useUserStore;
